#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>

int main()
{
    int sv[2];
    pid_t pid;
    char buffer[100];
    //创建套接字对
    if(socketpair(AF_UNIX,SOCK_STREAM,0,sv) == -1)
    {
        perror("socketpair");
        return 1;
    }
    pid = fork();
    if(pid == -1)
    {
        perror("fork");
        close(sv[0]);
        close(sv[1]);
        return 1;
    }
    else if(pid == 0)
    {
        //子进程
        close(sv[1]);//关闭子进程的写端
        ssize_t bytesRead = read(sv[0],buffer,sizeof(buffer));
        if(bytesRead == -1)
        {
            perror("read in child");
            return 1;
        }
        buffer[bytesRead] = '\0';
        printf("Child received: %s\n",buffer);
        close(sv[0]);
    }
    else{
        //父进程
        close(sv[0]);   //关闭父进程的读端
        const char *message = "Hello from parent!";
        ssize_t bytesWritten = write(sv[1],message,strlen(message));
        if(bytesWritten == -1)
        {
            perror("write in parent");
            return 1;
        }
        close(sv[1]);
    }
    return 0;
}